package com.pureut.order.service.impl;

import cn.hutool.core.convert.NumberChineseFormatter;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pureut.common.core.exception.GlobalException;
import com.pureut.common.core.utils.StringUtils;
import com.pureut.common.core.web.domain.AjaxResult;
import com.pureut.common.datascope.annotation.DataScope;
import com.pureut.common.security.utils.DictUtils;
import com.pureut.common.security.utils.SecurityUtils;
import com.pureut.order.domain.ProcurementPlanDetail;
import com.pureut.order.domain.PublicGoods;
import com.pureut.order.domain.PurchaseOrder;
import com.pureut.order.dto.PurchaseOrderDto;
import com.pureut.order.dto.PurchaseOrderQYWXDto;
import com.pureut.order.mapper.ProcurementPlanDetailMapper;
import com.pureut.order.mapper.PublicGoodsMapper;
import com.pureut.order.mapper.PurchaseOrderMapper;
import com.pureut.order.qiyeweixin.NumberToChinese;
import com.pureut.order.qiyeweixin.QiYeWeiXin;
import com.pureut.order.service.ProcurementPlanDetailService;
import com.pureut.order.service.PurchaseOrderService;
import com.pureut.order.vo.MaterialVo;
import com.pureut.order.vo.OrderReviewVo;
import com.pureut.order.vo.PurchaseOrderVo;
import com.pureut.order.vo.PurchaseVo;
import com.pureut.system.api.FeignService;
import com.pureut.system.api.StorageFegin;
import com.pureut.system.api.domain.SysDictData;
import com.pureut.system.api.vo.SysAuditHistoryVo;
import com.pureut.system.api.vo.SysWorkbenchAuditAgentVo;
import com.pureut.system.api.vo.UpdatePurchaseOrderDataVo;
import com.pureut.system.api.vo.UpdateReceiptStatusVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.logging.SimpleFormatter;
import java.util.stream.Collectors;

@Service
public class PurchaseOrderServiceImpl extends ServiceImpl<PurchaseOrderMapper, PurchaseOrder> implements PurchaseOrderService {


    @Resource
    PurchaseOrderMapper purchaseOrderMapper;

    @Resource
    ProcurementPlanDetailService procurementPlanDetailService;

    @Resource
    ProcurementPlanDetailMapper procurementPlanDetailMapper;

    @Resource
    FeignService feignService;

    @Resource
    StorageFegin storageFegin;

    @Resource
    PublicGoodsMapper publicGoodsMapper;


    /**
     * 采购订单列表
     */
    @Override
    @DataScope(deptAlias = "a")
    public List<PurchaseOrderDto> getList(PurchaseOrderVo purchaseOrderVo) {

        List<PurchaseOrderDto> purchaseOrderList = purchaseOrderMapper.getPurchaseOrderList(purchaseOrderVo);
        if (purchaseOrderList.size() == 0) {
            return new ArrayList<>();
        }
        //获取采购订单状态缓存字典数据
        List<SysDictData> statusArray = DictUtils.getDictCache("purchase_order_status");
        Map<String, String> actualMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        //单位
        List<SysDictData> materialUnitArray = DictUtils.getDictCache("sys_material_unit");
        Map<String, String> materialUnitMap = materialUnitArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        for (PurchaseOrderDto entity : purchaseOrderList) {
            entity.setUnitDict(materialUnitMap.get(String.valueOf(entity.getUnit())));
            entity.setStatusDict(actualMap.get(entity.getStatus()));
            //明细数据
            ProcurementPlanDetail one = procurementPlanDetailService.getOne(new QueryWrapper<ProcurementPlanDetail>().lambda().eq(ProcurementPlanDetail::getPurchasementNum, entity.getPurchasePlanNo()));
            if (one != null) {
                entity.setPlanWeight(one.getPlanWeight());
                entity.setDemandTime(one.getDemandTime());
                entity.setLowerWeight(one.getLowerWeight());
            }
        }
        return purchaseOrderList;
    }

    /**
     * 计划确认
     *
     * @param purchaseOrderVo
     * @return
     */
    @Override
    public boolean planConfirmation(PurchaseOrderVo purchaseOrderVo) throws Exception {
        //获取采购明细信息
        ProcurementPlanDetail procurementPlanDetail = procurementPlanDetailService.getById(purchaseOrderVo.getDetailId());
        if (1 == procurementPlanDetail.getStatus()) {
            PurchaseOrder purchaseOrder = new PurchaseOrder();
            purchaseOrder.setDeptId(SecurityUtils.getDeptId());
            //通过采购计划单号拼接采购订单号
            String[] split = procurementPlanDetail.getPurchasementNum().split("-");
            purchaseOrder.setPurchaseOrderNo("CD-" + split[1]);

            purchaseOrder.setStatus(1);
            purchaseOrder.setPurchasePlanNo(procurementPlanDetail.getPurchasementNum());
            purchaseOrder.setMaterialId(procurementPlanDetail.getMaterialId());
            purchaseOrder.setMaterialCategory(procurementPlanDetail.getMaterialCategory());
            purchaseOrder.setMaterialCode(procurementPlanDetail.getMaterialCode());
            purchaseOrder.setCreateTime(new Date());
            purchaseOrder.setPlanPrice(procurementPlanDetail.getPlannedUnitPrice());
            boolean save = save(purchaseOrder);
            if (save) {
                //同步该明细数据状态
                procurementPlanDetail.setStatus(6);
                procurementPlanDetailService.updateById(procurementPlanDetail);
            }
            return save;
        } else {
            throw new GlobalException("只能对预下单的单据进行确认");
        }

    }

    /**
     * 采购下单
     *
     * @param purchaseOrderVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateOrder(PurchaseOrderVo purchaseOrderVo) {
        PurchaseOrder purchaseOrder = getById(purchaseOrderVo.getId());
        if (1 == purchaseOrder.getStatus()) {
            purchaseOrder.setPurchaseContractNo(purchaseOrderVo.getPurchaseContractNo())
                    .setSupplierId(purchaseOrderVo.getSupplierId())
                    .setFirstBatchTime(purchaseOrderVo.getFirstBatchTime())
                    .setEndBatchTime(purchaseOrderVo.getEndBatchTime())
                    .setRemark(purchaseOrderVo.getRemark())
                    .setEnclosureUrl(purchaseOrderVo.getEnclosureUrl())
                    .setActualUnitPrice(purchaseOrderVo.getActualUnitPrice())
                    .setActualWeight(Double.parseDouble(purchaseOrderVo.getActualWeight()))
                    .setCreateBy(SecurityUtils.getUsername())
                    .setCreateTime(new Date())
                    .setStatus(2);
            return updateById(purchaseOrder);
        } else {
            throw new GlobalException("单据状态不为待下单，无法下单");
        }
    }

    /**
     * 提交审核
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean submitReview(Long id) {
        PurchaseOrder purchaseOrder = getById(id);
        if (2 == purchaseOrder.getStatus()) {
            purchaseOrder.setStatus(3);

            SysWorkbenchAuditAgentVo sysWorkbenchAuditAgentVo = new SysWorkbenchAuditAgentVo();
            sysWorkbenchAuditAgentVo.setDocConfig("order:purchase:order:review");
            sysWorkbenchAuditAgentVo.setReceiptName("采购订单");
            sysWorkbenchAuditAgentVo.setReceiptNumber(purchaseOrder.getPurchaseOrderNo());//供应商编号
            sysWorkbenchAuditAgentVo.setStatus(1);//待审核
            sysWorkbenchAuditAgentVo.setReceiptContent("有单据待审核,请及时审核");

            feignService.insertAuditAgent(sysWorkbenchAuditAgentVo);
            boolean b = updateById(purchaseOrder);
            //修改成功之后发送企业微信数据信息
            PurchaseOrderQYWXDto viewByIdQYWX = purchaseOrderMapper.getViewByIdQYWX(id);
            QiYeWeiXin qiYeWeiXin = new QiYeWeiXin();
            //采购单号
            String purchaseOrderNo = purchaseOrder.getPurchaseOrderNo();
            //供应商
            String supplierName = viewByIdQYWX.getSupplierName();
            //部门
            String deptName = viewByIdQYWX.getDeptName();
            //金额
            BigDecimal bigDecimal = new BigDecimal("0.00");
            if(StringUtils.isNotEmpty(viewByIdQYWX.getActualWeight()) && StringUtils.isNotEmpty(viewByIdQYWX.getActualUnitPrice())){
                bigDecimal = new BigDecimal(viewByIdQYWX.getActualWeight()).multiply(new BigDecimal(viewByIdQYWX.getActualUnitPrice())).setScale(2, RoundingMode.HALF_UP);
            }
            //金额转大写
            NumberToChinese numberToChinese = new NumberToChinese();
            String s = numberToChinese.toChinese(bigDecimal);
            //时间
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = sf.format(new Date());
                    //SCT283437T8R2pEF9GBNjJFaLVasCMtImr
            qiYeWeiXin.scSend("采购审批提醒:您有1笔采购订单待处理", "【核心信息】\n\n采购单号:" + purchaseOrderNo + "\n\n供应商:" + supplierName + "\n\n申请金额:¥" + bigDecimal + "(大写:" + s + ")\n\n申请部门:" + deptName + "\n\n申请时间:" + format + "\n\n访问链接:http://192.168.253.62:8282/", "SCT284408Tmg1pxuZTwxxn6IMmjUPnSkDy");
            return b;
        } else {
            throw new GlobalException("单据状态不为待提交，无法审核");
        }
    }

    /**
     * 撤销审核
     *
     * @param id
     * @return
     */
    @Override
    public boolean deleteReview(Long id) {
        PurchaseOrder purchaseOrder = getById(id);
        if (3 == purchaseOrder.getStatus()) {
            purchaseOrder.setStatus(2);

            //删除审核代办
            feignService.deleteDoc(purchaseOrder.getPurchaseOrderNo(),"采购订单");

            return updateById(purchaseOrder);
        } else {
            throw new GlobalException("单据状态不为待审核，无法撤销");
        }
    }

    /**
     * 关结
     *
     * @param purchaseOrderVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean closeReview(PurchaseOrderVo purchaseOrderVo) {
        PurchaseOrder purchaseOrder = getById(purchaseOrderVo.getId());
        if (purchaseOrder.getStatus() == 7 || purchaseOrder.getStatus() == 8) {
            throw new GlobalException("不能操作已完成、已关结的单据");
        }
        purchaseOrder.setStatus(8);
        purchaseOrder.setCloseReason(purchaseOrderVo.getCloseReason());
        //回传关节状态到采购计划明细
        ProcurementPlanDetail procurementPlanDetail = procurementPlanDetailMapper.selectOne(new QueryWrapper<ProcurementPlanDetail>().lambda().eq(ProcurementPlanDetail::getPurchasementNum, purchaseOrder.getPurchasePlanNo()));
        procurementPlanDetail.setStatus(5);
        procurementPlanDetailMapper.updateById(procurementPlanDetail);
        //同步已关结状态至采购入库页面
        UpdateReceiptStatusVo updateReceiptStatusVo = new UpdateReceiptStatusVo();
        updateReceiptStatusVo.setPurchaseOrderNo(purchaseOrder.getPurchaseOrderNo());
        updateReceiptStatusVo.setUpdateValue(4);
        try {
            storageFegin.updateReceiptStatus(updateReceiptStatusVo);
        } catch (Exception e) {
            throw new GlobalException("采购入库数据修改失败");
        }
        return updateById(purchaseOrder);
    }

    /**
     * 查看订单信息
     *
     * @param id
     * @return
     */
    @Override
    public PurchaseOrderDto getViewById(Long id) {
        PurchaseOrderDto purchaseOrderDto = purchaseOrderMapper.getViewById(id);
        //单位
        List<SysDictData> materialUnitArray = DictUtils.getDictCache("sys_material_unit");
        Map<String, String> materialUnitMap = materialUnitArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        ProcurementPlanDetail one = procurementPlanDetailService.getOne(new QueryWrapper<ProcurementPlanDetail>().lambda().eq(ProcurementPlanDetail::getPurchasementNum, purchaseOrderDto.getPurchasePlanNo()));

        //质量标准
        List<SysDictData> standardArray = DictUtils.getDictCache("quality_standard");
        Map<String, String> standardMap = standardArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        List<MaterialVo> materialVos = new ArrayList<>();
        MaterialVo materialVo = new MaterialVo();

        //获取下达重量
        ProcurementPlanDetail procurementPlanDetail = procurementPlanDetailMapper.selectOne(new QueryWrapper<ProcurementPlanDetail>().lambda().eq(ProcurementPlanDetail::getPurchasementNum, purchaseOrderDto.getPurchasePlanNo()));
        materialVo.setLowerWeight(procurementPlanDetail.getLowerWeight());
        materialVo.setUnitDict(materialUnitMap.get(String.valueOf(purchaseOrderDto.getUnit())));
        materialVo.setPlannedUnitPrice(one.getPlannedUnitPrice());
        materialVo.setPlanWeight(one.getPlanWeight());
        materialVo.setMaterialCode(purchaseOrderDto.getMaterialCode());
        materialVo.setMaterialName(purchaseOrderDto.getMaterialName());
        materialVo.setMaterialId(purchaseOrderDto.getMaterialId());
        materialVo.setActualUnitPrice(purchaseOrderDto.getActualUnitPrice());
        materialVo.setActualWeight(purchaseOrderDto.getActualWeight());
        materialVo.setQualityStandard(String.valueOf(one.getQualityStandard()));
        materialVo.setQualityStandardDict(standardMap.get(String.valueOf(one.getQualityStandard())));
        materialVos.add(materialVo);
        purchaseOrderDto.setMaterialList(materialVos);

        return purchaseOrderDto;
    }

    /**
     * 批次到货
     *
     * @param purchaseOrderDto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchArrival(com.pureut.system.api.dto.PurchaseOrderDto purchaseOrderDto) {
        PurchaseOrder purchaseOrder = getById(purchaseOrderDto.getId());
        if (purchaseOrder.getStatus() == 5 || purchaseOrder.getStatus() == 6) {
            AjaxResult ajaxResult = storageFegin.batchArrival(purchaseOrderDto);
            String code = ajaxResult.get("code").toString();
            if ("200".equals(code)) {
                purchaseOrder.setEstimatedTime(purchaseOrderDto.getEstimatedTime());
                return updateById(purchaseOrder);
            } else {
                return false;
            }
        } else {
            throw new GlobalException("只能操作待到货和批次到货得数据!");
        }
    }


//            //实际到货量-退货量≥下达量时候为已完成,否则改为部分到货
//            BigDecimal add;
//            if (purchaseOrder.getActualArrivalWeight() == 0) {
//                //如果实际到货量为空，必然不满足实际到货量-退货量≥下达量的条件
//                purchaseOrder.setStatus(6);
//                //同步部分到货状态至采购计划
//                ProcurementPlanDetail procurementPlanDetail = procurementPlanDetailMapper.selectOne(new QueryWrapper<ProcurementPlanDetail>().lambda().eq(ProcurementPlanDetail::getPurchasementNum, purchaseOrder.getPurchasePlanNo()));
//                procurementPlanDetail.setStatus(3);
//                procurementPlanDetailService.updateById(procurementPlanDetail);
//            } else {
//                //获取实际到货量
//                add = BigDecimal.valueOf(purchaseOrder.getActualArrivalWeight());
//                //获取退货重量
//                BigDecimal backWeight = BigDecimal.valueOf(purchaseOrder.getBackWeight());
//                //实际到货量-退货量
//                int subtract = (int) Math.round(add.subtract(backWeight).doubleValue());
//                //通过采购计划获取实际量
//                int actualWeight =(int) Math.round(purchaseOrder.getActualWeight());
//
//                if (subtract >= actualWeight) {
//                    purchaseOrder.setStatus(7);
//                    //同步已完成状态至采购入库页面
//                    UpdateReceiptStatusVo updateReceiptStatusVo = new UpdateReceiptStatusVo();
//                    updateReceiptStatusVo.setPurchaseOrderNo(purchaseOrder.getPurchaseOrderNo());
//                    updateReceiptStatusVo.setUpdateValue(3);
//                    storageFegin.updateReceiptStatus(updateReceiptStatusVo);
//                    //同步完成状态至采购计划
//                    ProcurementPlanDetail procurementPlanDetail = procurementPlanDetailMapper.selectOne(new QueryWrapper<ProcurementPlanDetail>().lambda().eq(ProcurementPlanDetail::getPurchasementNum, purchaseOrder.getPurchasePlanNo()));
//                    procurementPlanDetail.setStatus(4);
//                    procurementPlanDetailService.updateById(procurementPlanDetail);
//                } else {
//                    purchaseOrder.setStatus(6);
//                    //同步部分到货状态至采购计划
//                    ProcurementPlanDetail procurementPlanDetail = procurementPlanDetailMapper.selectOne(new QueryWrapper<ProcurementPlanDetail>().lambda().eq(ProcurementPlanDetail::getPurchasementNum, purchaseOrder.getPurchasePlanNo()));
//                    procurementPlanDetail.setStatus(3);
//                    procurementPlanDetailService.updateById(procurementPlanDetail);
//                }


    /**
     * 修改
     *
     * @param purchaseOrderVo
     * @return
     */
    @Override
    public boolean updateOrderById(PurchaseOrderVo purchaseOrderVo) {

        PurchaseOrder purchaseOrder = getById(purchaseOrderVo.getId());
        if (purchaseOrder.getStatus() == 2 || purchaseOrder.getStatus() == 9) {
            purchaseOrder.setPurchaseContractNo(purchaseOrderVo.getPurchaseContractNo())
                    .setSupplierId(purchaseOrderVo.getSupplierId())
                    .setFirstBatchTime(purchaseOrderVo.getFirstBatchTime())
                    .setEndBatchTime(purchaseOrderVo.getEndBatchTime())
                    .setRemark(purchaseOrderVo.getRemark())
                    .setEnclosureUrl(purchaseOrderVo.getEnclosureUrl());

            List<PurchaseVo> orderList = purchaseOrderVo.getMaterialList();
            for (PurchaseVo entity : orderList) {
                purchaseOrder.setActualWeight(Double.parseDouble(entity.getActualWeight()));
                purchaseOrder.setActualUnitPrice(entity.getActualUnitPrice());
            }

            //调用审核
            if (purchaseOrder.getStatus() == 9) {
                SysAuditHistoryVo sysAuditHistoryVo = new SysAuditHistoryVo();
                String perms = "order:purchase:order:review";
                String auditDoc = purchaseOrder.getPurchaseOrderNo();
                sysAuditHistoryVo.setAuditDoc(auditDoc);
                sysAuditHistoryVo.setPerms(perms);
                AjaxResult history = feignService.editHistory(sysAuditHistoryVo);
                String data = JSON.parseObject(JSON.toJSONString(history.get("msg")), String.class);
                if ("操作成功".equals(data)) {
                    purchaseOrder.setStatus(2);

                    //修改审核代办状态为已处理
                    feignService.updateStatus(3,purchaseOrder.getPurchaseOrderNo(),"采购订单");//



                    return updateById(purchaseOrder);
                } else {
                    return false;
                }
            }
            return updateById(purchaseOrder);
        } else {
            throw new GlobalException("只有待提交和未通过的单据才能进行修改");
        }

    }

    /**
     * 单据审核
     *
     * @param orderReviewVo
     * @return
     */
    @Override
    public boolean purchaseOrderReview(OrderReviewVo orderReviewVo) {

        PurchaseOrder purchaseOrder = getById(orderReviewVo.getId());
        if (purchaseOrder.getStatus() == 3 || purchaseOrder.getStatus() == 4) {
            String perms = "order:purchase:order:review";
            int isAdopt = orderReviewVo.getIsAdopt();
            String auditDoc = purchaseOrder.getPurchaseOrderNo();
            String auditRemarks = orderReviewVo.getReviewComments();
            Long userId = SecurityUtils.getUserId();
            AjaxResult sequence = feignService.getSequenceTwo(perms, 2, isAdopt, auditRemarks, auditDoc, userId);
            Integer data = JSON.parseObject(JSON.toJSONString(sequence.get("data")), Integer.class);
            if (data == null) {
                throw new GlobalException("未对该审核进行配置");
            }
            //1:通过，2：审核中，3：没权限 4:该人已经审核过
            if (orderReviewVo.getIsAdopt() == 1) {
                if (data == 1) {
                    purchaseOrder.setStatus(5);
                    if (purchaseOrder.getReviewBy() == null) {
                        purchaseOrder.setReviewBy(SecurityUtils.getUsername());
                    } else {
                        purchaseOrder.setReviewBy(purchaseOrder.getReviewBy() + "," + SecurityUtils.getUsername());
                    }
                    purchaseOrder.setReviewTime(new Date());
                    //回传待到货数据到采购计划
                    ProcurementPlanDetail procurementPlanDetail = procurementPlanDetailMapper.selectOne(new QueryWrapper<ProcurementPlanDetail>().lambda().eq(ProcurementPlanDetail::getPurchasementNum, purchaseOrder.getPurchasePlanNo()));
                    procurementPlanDetail.setStatus(2);
                    procurementPlanDetailMapper.updateById(procurementPlanDetail);

                    //修改审核代办状态
                    feignService.updateStatus(3,purchaseOrder.getPurchaseOrderNo(),"采购订单");

                    return updateById(purchaseOrder);
                } else if (data == 2) {
                    purchaseOrder.setStatus(4);
                    if (purchaseOrder.getReviewBy() == null) {
                        purchaseOrder.setReviewBy(SecurityUtils.getUsername());
                    } else {
                        purchaseOrder.setReviewBy(purchaseOrder.getReviewBy() + "," + SecurityUtils.getUsername());
                    }
                    purchaseOrder.setReviewTime(new Date());
                    return updateById(purchaseOrder);
                } else if (data == 3) {
                    throw new GlobalException("没有审核权限");
                } else {
                    throw new GlobalException("该用户已经审核过");
                }
            } else {
                if (data == 1 || data == 2) {
                    purchaseOrder.setStatus(9);
                    if (purchaseOrder.getReviewBy() == null) {
                        purchaseOrder.setReviewBy(SecurityUtils.getUsername());
                    } else {
                        purchaseOrder.setReviewBy(purchaseOrder.getReviewBy() + "," + SecurityUtils.getUsername());
                    }
                    purchaseOrder.setReviewTime(new Date());

                    SysWorkbenchAuditAgentVo sysWorkbenchAuditAgentVo = new SysWorkbenchAuditAgentVo();
                    sysWorkbenchAuditAgentVo.setDocConfig("order:purchase:order:review");
                    sysWorkbenchAuditAgentVo.setReceiptName("采购订单");
                    sysWorkbenchAuditAgentVo.setReceiptNumber(purchaseOrder.getPurchaseOrderNo());//采购订单号
                    sysWorkbenchAuditAgentVo.setStatus(2);//待处理
                    sysWorkbenchAuditAgentVo.setPassFlag("1");
                    sysWorkbenchAuditAgentVo.setCreateName(purchaseOrder.getCreateBy());
                    sysWorkbenchAuditAgentVo.setReceiptContent("有单据未通过,请及时查看");

                    feignService.insertAuditAgent(sysWorkbenchAuditAgentVo);

                    return updateById(purchaseOrder);
                } else if (data == 3) {
                    throw new GlobalException("没有审核权限");
                } else {
                    throw new GlobalException("该用户已经审核过");
                }
            }
        } else {
            throw new GlobalException("状态为待审核和审核中的单据才能进行审核");
        }
    }

    /**
     * 修改采购订单数据（feign调用）
     *
     * @param updatePurchaseOrderDataVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateOrderData(UpdatePurchaseOrderDataVo updatePurchaseOrderDataVo) {

        //根据采购订单号获取采购订单数据
        PurchaseOrder purchaseOrder = purchaseOrderMapper.selectOne(new QueryWrapper<PurchaseOrder>().lambda().eq(PurchaseOrder::getPurchaseOrderNo, updatePurchaseOrderDataVo.getPurchaseOrderNo()));
        //获取实际到货重量
        double v = Double.parseDouble(updatePurchaseOrderDataVo.getActualQuantity());
        purchaseOrder.setActualArrivalWeight(v);
        double actualWeight = purchaseOrder.getActualWeight();
        //如果 实际到货量≥实际量：完成；如果 实际到货量小于实际量：部分到货
        if ((int) Math.round(v) >= (int) Math.round(actualWeight)) {
            purchaseOrder.setStatus(7);
            //回传采购计划状态
            ProcurementPlanDetail procurementPlanDetail = procurementPlanDetailMapper.selectOne(new QueryWrapper<ProcurementPlanDetail>().lambda().eq(ProcurementPlanDetail::getPurchasementNum, purchaseOrder.getPurchasePlanNo()));
            procurementPlanDetail.setStatus(4);
            procurementPlanDetailService.updateById(procurementPlanDetail);
        } else {
            purchaseOrder.setStatus(6);
            //回传采购计划状态
            ProcurementPlanDetail procurementPlanDetail = procurementPlanDetailMapper.selectOne(new QueryWrapper<ProcurementPlanDetail>().lambda().eq(ProcurementPlanDetail::getPurchasementNum, purchaseOrder.getPurchasePlanNo()));
            procurementPlanDetail.setStatus(3);
            procurementPlanDetailService.updateById(procurementPlanDetail);
        }
        return updateById(purchaseOrder);
    }

    /**
     * 采购订单退货重量累加
     *
     * @param updatePurchaseOrderDataVo
     * @return
     */
    @Override
    public boolean updateSalesReturn(UpdatePurchaseOrderDataVo updatePurchaseOrderDataVo) {
        //退货重量
        String actualQuantity = updatePurchaseOrderDataVo.getActualQuantity();

        //查询订单重量
        PurchaseOrder purchaseOrder = purchaseOrderMapper.selectOne(new QueryWrapper<PurchaseOrder>().lambda().eq(PurchaseOrder::getPurchaseOrderNo, updatePurchaseOrderDataVo.getPurchaseOrderNo()));

        //查询采购订单中的物料单位是否是吨
        PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, purchaseOrder.getMaterialCode()));

        if ("3".equals(publicGoods.getMaterialUnit())){
            BigDecimal bigDecimal = new BigDecimal(actualQuantity);
            BigDecimal bigDecimal1 = new BigDecimal("1000");
            BigDecimal divide = bigDecimal1.divide(bigDecimal1);
            actualQuantity = String.valueOf(divide);
        }

        BigDecimal bigDecimal = new BigDecimal(actualQuantity);

        BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(purchaseOrder.getBackWeight()));

        BigDecimal add = bigDecimal.add(bigDecimal1);



        purchaseOrder.setBackWeight(add.doubleValue());
        boolean b = updateById(purchaseOrder);
        return b;
    }

    /**
     * 修改采购订单退货重量feign扣除
     *
     * @param updatePurchaseOrderDataVo
     * @return
     */
    @Override
    public boolean updateDeductSalesReturn(UpdatePurchaseOrderDataVo updatePurchaseOrderDataVo) {
        //退货重量
        String actualQuantity = updatePurchaseOrderDataVo.getActualQuantity();

        //查询订单重量
        PurchaseOrder purchaseOrder = purchaseOrderMapper.selectOne(new QueryWrapper<PurchaseOrder>().lambda().eq(PurchaseOrder::getPurchaseOrderNo, updatePurchaseOrderDataVo.getPurchaseOrderNo()));

        BigDecimal bigDecimal = new BigDecimal(actualQuantity);

        BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(purchaseOrder.getBackWeight()));

        BigDecimal add = bigDecimal1.subtract(bigDecimal);
        purchaseOrder.setBackWeight(add.doubleValue());

        return updateById(purchaseOrder);
    }
}
